<template>
  <div
    v-loading="loading"
    style="display: flex; flex-direction: column; flex: 1"
    element-loading-text="加载中..."
  >
    <!-- header -->
    <div class="top_app">
      <div class="top_h">
        <div class="text">
          <span class="module_color">出库详情</span>
          <el-tag class="ml-2" type="warning" v-if="DetailStore?.status == 1">待审核</el-tag>
          <el-tag type="warning" v-if="DetailStore?.status == 2">待出库</el-tag>
          <el-tag class="purple_tag" v-if="DetailStore?.status == 3">已驳回</el-tag>
          <el-tag class="ml-2" type="success" v-if="DetailStore?.status == 4">已出库</el-tag>
          <el-tag type="info" v-if="DetailStore?.status == 5">已作废</el-tag>
        </div>
        <div class="btns">
          <template v-if="DetailStore?.status == 2">
            <el-button class="btn_cancel" @click="cancellationBtn">作废</el-button>
            <el-button color="#007cff" plain class="btn_save" @click="outboundBtn">出库</el-button>
          </template>
          <el-button color="#007cff" class="btn_save" @click="printBtn">打印</el-button>
        </div>
      </div>
    </div>

    <!-- main -->
    <div class="app-container" style="height: 100%">
      <div class="mark_bg">
        <div class="content_inner">
          <!-- 基本信息 -->
          <h4 class="title_bl">出库信息</h4>
          <el-form label-width="90px" :model="orderDetail" class="basic_information">
            <el-row>
              <el-col :lg="6" :sm="12">
                <el-form-item label="出库单号:">
                  <span class="ml">{{ DetailStore?.outboundNo }}</span>
                </el-form-item>
                <el-form-item label="单据类型:">
                  <span class="ml">{{ DetailStore?.type }}</span>
                </el-form-item>
                <el-form-item label="仓库类型:">
                  <span class="ml">{{ storeType[DetailStore?.storeType]?.title }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="收货类型:">
                  <span class="ml">{{
                    receiptAddrType[DetailStore?.receiptAddrType - 1]?.title
                  }}</span>
                </el-form-item>
                <el-form-item label="收货名称:">
                  <span class="ml">
                    {{ DetailStore?.receiptName }}&nbsp;{{ DetailStore?.receiptPhone }}</span
                  >
                </el-form-item>
                <el-form-item label="收货地址:">
                  <span class="ml">
                    {{
                      DetailStore?.receiptProvince +
                      DetailStore?.receiptCity +
                      DetailStore?.receiptArea +
                      DetailStore?.receiptTown +
                      DetailStore?.receiptAddress
                    }}</span
                  >
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="制单日期:">
                  <span class="ml">{{ DetailStore?.createTime }}</span>
                </el-form-item>
                <el-form-item label="预计出库时间:">
                  <span class="ml"> {{ DetailStore?.estimateTime }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="单据来源:">
                  <span class="ml">{{ source[DetailStore?.source - 1]?.title }}</span>
                </el-form-item>
                <el-form-item label="单据备注:">
                  <span class="ml"> {{ DetailStore?.remark }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="content_inner" style="display: flex; flex-direction: column; flex: 1">
          <h4 class="title_bl">商品信息</h4>
          <div style="flex: 1; position: relative">
            <el-table
              :border="true"
              :data="StoreDetailGoodsList"
              height="100%"
              show-summary
              :summary-method="getSummaries"
              resizable
              stripe
              style="width: 100%; position: absolute"
              :header-cell-style="tableHeaderCellStyle"
            >
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <el-table-column label="序号" fixed width="50" type="index" />
              <el-table-column show-overflow-tooltip label="商品类型" width="80">
                <template v-slot="i">
                  {{ i.row.type == 1 ? '成品' : '配件' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="goodsName"
                show-overflow-tooltip
                label="名称"
                min-width="100"
              />
              <el-table-column
                prop="goodsModel"
                show-overflow-tooltip
                label="型号"
                min-width="100"
              />
              <el-table-column
                prop="goodsSpecName"
                show-overflow-tooltip
                label="规格"
                min-width="100"
              />
              <el-table-column
                prop="goodsBrand"
                show-overflow-tooltip
                label="品牌"
                min-width="100"
              />
              <el-table-column
                prop="goodsType"
                show-overflow-tooltip
                label="分类"
                min-width="120"
              />
              <el-table-column prop="goodsUnit" show-overflow-tooltip label="单位" width="100" />
              <el-table-column prop="store" show-overflow-tooltip label="仓库" min-width="150" />
              <el-table-column
                prop="storePosition"
                show-overflow-tooltip
                label="仓位"
                min-width="150"
              />
              <el-table-column
                prop="systemStock"
                show-overflow-tooltip
                label="即时库存"
                align="right"
                width="90"
              />
              <el-table-column
                prop="qty"
                show-overflow-tooltip
                label="出库数量"
                align="right"
                width="90"
              />
              <el-table-column
                prop="stockCodeVos"
                show-overflow-tooltip
                label="一物一码"
                min-width="160"
              >
                <template v-slot="i">
                  <el-tooltip
                    v-if="i.row.stockCodeVos?.length > 0"
                    :content="i.row.stockCodeVos.map((o) => o.code).join()"
                    effect="dark"
                    placement="top"
                  >
                    <span class="number" @click="getCode(i.row, i.$index)">
                      {{ i.row.stockCodeVos[0].code }}
                    </span>
                  </el-tooltip>
                  <HLink v-else @click="getCode(i.row, i.$index)"> 一物一码</HLink>
                </template>
              </el-table-column>
              <el-table-column
                prop="price"
                show-overflow-tooltip
                label="金额"
                align="right"
                width="100"
              >
                <template v-slot="i"> ￥{{ i.row.price.toFixed(2) }} </template>
              </el-table-column>
              <el-table-column prop="remark" show-overflow-tooltip label="备注" width="100" />
            </el-table>
          </div>
        </div>
        <div class="content_inner">
          <!-- 出库信息 -->
          <!-- 物流信息 -->
          <h4 class="title_bl" v-if="DetailStore?.status == 4">物流信息</h4>
          <el-form
            v-if="DetailStore?.status == 4"
            label-width="90px"
            :model="orderDetail"
            class="basic_information"
          >
            <el-row v-if="DetailStore?.status == 4">
              <el-col :lg="6" :sm="12">
                <el-form-item label="物流名称:">
                  <span class="ml">{{ DetailStore?.logisticsName }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="单号:">
                  <span class="ml"> {{ DetailStore?.logisticsNo }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="物流备注:">
                  <span class="ml"> {{ DetailStore?.logisticsRemark }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <h4 class="title_bl">出库信息</h4>
          <el-form label-width="90px" :model="orderDetail" class="basic_information">
            <el-row>
              <el-col :lg="6" :sm="12">
                <el-form-item label="制单人:">
                  <span class="ml">{{ DetailStore?.createEmp }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="审核人:">
                  <span class="ml">{{ DetailStore?.reviewEmp }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="审核时间:">
                  <span class="ml"> {{ DetailStore?.reviewTime }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="审核备注:">
                  <span class="ml"> {{ DetailStore?.reviewRemark }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="DetailStore?.rejectTime">
              <el-col :lg="6" :sm="12">
                <el-form-item label="驳回单操作人:">
                  <span class="ml">{{ DetailStore?.rejectEmp }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="驳回时间:">
                  <span class="ml"> {{ DetailStore?.rejectTime }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="驳回备注:">
                  <span class="ml"> {{ DetailStore?.rejectRemark }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12"> </el-col>
            </el-row>
            <el-row v-if="DetailStore?.cancelTime">
              <el-col :lg="6" :sm="12">
                <el-form-item label="作废单操作人:">
                  <span class="ml">{{ DetailStore?.cancelEmp }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="作废时间:">
                  <span class="ml"> {{ DetailStore?.cancelTime }}</span>
                </el-form-item>
              </el-col>
              <el-col :lg="6" :sm="12">
                <el-form-item label="作废备注:">
                  <span class="ml"> {{ DetailStore?.cancelRemark }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 作废弹窗 -->
    <HModal v-model="cancellationDialog" width="auto">
      <template #header>
        <div class="cancellation_dialog">
          <el-icon size="20"> <WarningFilled /> </el-icon>作废确认
        </div>
      </template>
      <el-form label-position="top">
        <el-form-item label="确认作废此出库吗?">
          <el-input
            v-model="remark"
            maxlength="400"
            placeholder="可填写作废原因"
            type="textarea"
            class="reject_form_input"
            resize="both"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="cancellationConfirm">确认</HButton>
        <HButton is-modal @click=";(cancellationDialog = false), (remark = '')">取消</HButton>
      </template>
    </HModal>

    <!-- 出库弹窗 -->
    <HModal v-model="outboundDialog" title="选择出库物流" :width="600">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="80px"
        class="form_content"
        @validate="handleOutStoreFormValidate"
      >
        <!--发货人-->
        <el-form-item
          label="发货人"
          prop="sendName"
          :class="{
            form_item: outStoreFormValidateResult['sendName'],
            validate_fail: !outStoreFormValidateResult['sendName'],
          }"
        >
          <el-select
            placeholder="请选择"
            filterable
            clearable
            v-model="ruleForm.sendStoreId"
            style="width: 100%"
            :filter-method="inputValueSch"
            @change="changestoreId"
            :loading="loadingEmp"
            remote-show-suffix
          >
            <el-option
              v-for="item in modules"
              :key="item.id"
              :value="item.id"
              :label="item.userName"
            />
          </el-select>
        </el-form-item>

        <!--手机号码-->
        <el-form-item
          label="手机号码"
          prop="sendPhone"
          :class="{
            form_item: outStoreFormValidateResult['sendPhone'],
            validate_fail: !outStoreFormValidateResult['sendPhone'],
          }"
        >
          <el-input v-model="ruleForm.sendPhone" placeholder="手机号码" />
        </el-form-item>

        <!--发货地址-->
        <el-form-item
          label="发货地址"
          prop="sendProvince"
          :class="{
            form_item: outStoreFormValidateResult['sendProvince'],
            validate_fail: !outStoreFormValidateResult['sendProvince'],
          }"
        >
          <SingleAddress ref="addrsDom" :address="addrsObj" @value-change="addressValChange" />
        </el-form-item>

        <!--详细地址-->
        <el-form-item
          label="详细地址"
          prop="sendAddress"
          :class="{
            form_item: outStoreFormValidateResult['sendAddress'],
            validate_fail: !outStoreFormValidateResult['sendAddress'],
          }"
        >
          <el-input v-model="ruleForm.sendAddress" placeholder="详细地址" />
        </el-form-item>

        <!--物流名称-->
        <el-form-item label="物流名称" prop="logisticsName" class="form_item">
          <el-select
            placeholder="物流名称"
            filterable
            clearable
            v-model="ruleForm.logisticsName"
            style="width: 100%"
            :filter-method="inputValueLog"
            :loading="loadingEmp"
            remote-show-suffix
          >
            <el-option
              v-for="item in Logistics"
              :key="item.name"
              :value="item.name"
              :label="item.name"
            />
          </el-select>
        </el-form-item>

        <!--物流编码-->
        <el-form-item label="物流编码" class="form_item">
          <el-select
            placeholder="物流编码"
            filterable
            disabled
            v-model="ruleForm.logisticsCode"
            style="width: 100%"
          >
            <el-option
              v-for="item in Logistics"
              :key="item.code"
              :value="item.code"
              :label="item.code"
            />
          </el-select>
        </el-form-item>

        <!--物流单号-->
        <el-form-item label="物流单号" prop="logisticsNo" class="form_item">
          <el-input v-model="ruleForm.logisticsNo" placeholder="物流单号" />
        </el-form-item>

        <!--出库备注-->
        <el-form-item label="出库备注" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            maxlength="400"
            placeholder="备注"
            type="textarea"
            :rows="1"
          />
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="outboundConfirm">确认</HButton>
        <HButton is-modal @click="onOutStoreCancel">取消</HButton>
      </template>
    </HModal>

    <!-- 一物一码详情 -->
    <HModal v-model="getCodeDialog" title="一物一码详情" :width="1000">
      <div>
        <div class="header_code">
          <HPlainButton v-if="DetailStore?.status == 2" @click="getCodeDataShow"
            >在库选择</HPlainButton
          >
          <div class="code_info">
            <p
              >出库编码总数：<span>{{ codeRowObj.qty }}</span></p
            >
            <p
              >已录入总数：<span>{{
                StoreDetailGoodsList[codeRowObj.index].stockCodeVosTemp.length
              }}</span></p
            >
            <p
              >未录入总数：<span>{{
                codeRowObj.qty - StoreDetailGoodsList[codeRowObj.index].stockCodeVosTemp.length
              }}</span></p
            >
          </div>
        </div>
        <el-table
          :border="true"
          :data="StoreDetailGoodsList[codeRowObj.index].stockCodeVosTemp"
          height="50vh"
          resizable
          stripe
          style="width: 100%"
          :header-cell-style="tableHeaderCellStyle"
        >
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
          <el-table-column v-if="DetailStore?.status == 2" label="序号" width="70" fixed>
            <template v-slot="scope">
              <span class="order"> {{ scope.$index + 1 }} </span>
              <span class="add_delete">
                <el-icon size="16" color="#007cff" class="add" @click="getCodeDataShow">
                  <CirclePlus />
                </el-icon>
                <el-icon color="rgba(245, 108, 108, 1)" size="16" @click="deteleCode(scope.$index)">
                  <Delete />
                </el-icon>
              </span>
            </template>
          </el-table-column>
          <el-table-column v-else label="序号" type="index" width="50" fixed></el-table-column>
          <el-table-column label="一物一码" prop="code" show-overflow-tooltip></el-table-column>
          <el-table-column label="品牌" prop="goodsBrand" show-overflow-tooltip></el-table-column>
          <el-table-column label="名称" prop="goodsName" show-overflow-tooltip></el-table-column>
          <el-table-column label="型号" prop="goodsModel" show-overflow-tooltip></el-table-column>
          <el-table-column
            label="规格"
            prop="goodsSpecName"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="所属仓库" prop="store" show-overflow-tooltip></el-table-column>
          <el-table-column
            label="仓位"
            prop="storePosition"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
      </div>
      <template #footerRight>
        <HButton is-modal type="primary" @click="confirmCode">确定</HButton>
        <HButton is-modal @click="getCodeDialog = false">取消</HButton>
      </template>
    </HModal>

    <!-- 在库选择 -->
    <HModal v-model="SelectCodeDialog" title="在库选择" :width="1000">
      <div v-loading="getStoreCodeListLoading">
        <div class="header_code">
          <div class="left_text">
            <p
              >商品名称：<span>{{ codeRowObj.goodsName }}</span></p
            >
            <p
              >商品分类：<span>{{ codeRowObj.goodsType }}</span></p
            >
            <p
              >商品规格：<span>{{ codeRowObj.goodsSpecName }}</span></p
            >
            <p
              >商品编号：<span>{{ codeRowObj.code }}</span></p
            >
          </div>
          <div class="btn_header_code">
            <div style="margin-right: 5px">
              <HPlainButton @click="onCreateCode">创建编码</HPlainButton>
            </div>
            <el-input
              clearable
              v-model="keywordCode"
              placeholder="一物一码"
              @keyup.enter="getInStoreCodeListData"
            >
              <template #append>
                <el-button class="btn_search" :icon="Search" @click="getInStoreCodeListData" />
              </template>
            </el-input>
          </div>
        </div>
        <el-table
          :border="true"
          :data="getListCode"
          height="50vh"
          @select-all="selectAllCodeinformation"
          ref="selectCodeRef"
          @select="handleClickCodeinformation"
          resizable
          stripe
          style="width: 100%"
          :header-cell-style="tableHeaderCellStyle"
        >
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
          <el-table-column show-overflow-tooltip type="selection" width="40" fixed />
          <el-table-column label="序号" width="60" type="index" fixed></el-table-column>
          <el-table-column label="一物一码" prop="code" show-overflow-tooltip></el-table-column>
          <el-table-column label="品牌" prop="goodsBrand" show-overflow-tooltip></el-table-column>
          <el-table-column label="名称" prop="goodsName" show-overflow-tooltip></el-table-column>
          <el-table-column label="型号" prop="goodsModel" show-overflow-tooltip></el-table-column>
          <el-table-column
            label="规格"
            prop="goodsSpecName"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="所属仓库" prop="store" show-overflow-tooltip></el-table-column>
          <el-table-column
            label="仓位"
            prop="storePosition"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
        <div class="footer_code">
          <Pagination
            ref="paginationRef"
            :list_total="totalCode"
            @size-change="getInStoreCodeListData"
            @current-change="getInStoreCodeListData"
          />
        </div>
      </div>
      <template #footerRight>
        <HButton is-modal type="primary" @click="confirmSelectCode">确定</HButton>
        <HButton is-modal @click="SelectCodeDialog = false">取消</HButton>
      </template>
    </HModal>

    <!-- 创建编码弹窗 -->
    <HModal v-model="CreateCodeDialog" title="创建一物一码">
      <el-form
        ref="createCodeRef"
        :model="createCode"
        :rules="CreateCoderules"
        label-width="90px"
        class="newOut-ruleForm"
      >
        <el-form-item label="批次名称" prop="name">
          <el-input v-model="createCode.name" placeholder="请输入批次名称" />
        </el-form-item>
        <el-form-item label="编码类型">
          <el-radio-group v-model="createCode.type" disabled class="ml-4">
            <el-radio :value="1">成品</el-radio>
            <el-radio :value="2">配件</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品型号">
          <el-input disabled v-model="codeRowObj.goodsModel" placeholder="商品型号" />
        </el-form-item>
        <el-form-item label="商品规格">
          <el-input disabled v-model="codeRowObj.goodsSpecName" placeholder="商品规格" />
        </el-form-item>
        <el-form-item label="编码数量">
          <el-input
            v-model="createCode.codeVos[0].qty"
            @input="createCode.codeVos[0].qty = createCode.codeVos[0].qty.replace(/[^0-9]/g, '')"
            placeholder="编码数量"
          />
        </el-form-item>
        <el-form-item label="质保周期">
          <el-input
            v-model="createCode.codeVos[0].warrantyDay"
            @input="
              createCode.codeVos[0].warrantyDay = createCode.codeVos[0].warrantyDay.replace(
                /[^0-9]/g,
                '',
              )
            "
            placeholder="质保周期"
          />
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onaddSave">确认</HButton>
        <HButton is-modal @click="CreateCodeDialog = false">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick, watch } from 'vue'
  import { useRoute } from 'vue-router'
  import { CirclePlus, Delete, Search, WarningFilled } from '@element-plus/icons-vue'
  import { phone, setProvince } from '@/utils/validate'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import * as _ from 'lodash'
  import { tableHeaderCellStyle } from '@/utils/tools'
  import { ElMessage, FormItemProp } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import {
    getOutboundMaterial,
    getOutboundDetail,
    cancelStoreOutbound,
    getStoreCodeList,
    storeEmpAddressPageSelect,
    saveSureStoreOutbound,
    getLogisticsSelectList,
  } from '@/api/store'
  import { addSave } from '@/api/code'
  import userOutbound from './userOutbound'
  import { HButton, HLink, HModal, HPlainButton } from '@/components/common'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.storage.outStorageDetail,
  })

  let { storeType, receiptAddrType, source } = userOutbound()

  const cancellationDialog = ref(false)
  const outboundDialog = ref(false)
  const route = useRoute()
  const dom = ref()
  const StoreDetailGoodsList = ref()
  const orderDetail = ref(null) //工单详情
  const loading = ref(false)
  const DetailStore = ref(null)
  const remark = ref('') //作废消备注
  const ruleFormRef = ref()
  const addrsDom = ref()
  const addrsObj = ref({
    province: '',
    city: '',
    area: '',
    town: '',
  })
  const ruleForm = ref({
    logisticsCode: '', //物流编码
    logisticsName: '', //物流名称
    logisticsNo: '', //物流单号
    remark: '', //出库备注
    outBoundMaterialVos: [],
    sendStoreId: null,
    sendAddress: '', // 发货人地址 -详细地址
    sendName: '', //发货人姓名
    sendPhone: '', //发货人手机号

    sendArea: '', //发货人地址 -县/区
    sendCity: '', //发货人地址 -市
    sendProvince: '', //发货人地址 -省
    sendTown: '', //发货人地址 -镇
  })
  const rules = ref({
    sendAddress: [{ required: true, message: '详细地址', trigger: ['blur', 'change'] }], // 发货人地址 -详细地址
    sendName: [{ required: true, message: '发货人姓名', trigger: ['blur', 'change'] }], //发货人姓名
    sendPhone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: phone(ruleForm.value.sendPhone), trigger: 'blur' },
    ],
    sendProvince: [
      {
        required: true,
        validator: setProvince(ruleForm.value.sendProvince),
        trigger: ['blur', 'change'],
      },
    ],
  })

  const CreateCoderules = ref({
    name: [{ required: true, message: '批次名称', trigger: ['blur', 'change'] }],
  })
  const keywordCode = ref('')
  const getStoreCodeListLoading = ref(false)
  // const orderGoodsList = ref([])
  // 获取一物一码
  const getCodeDialog = ref(false) //弹窗
  const codeRowObj = ref(null)
  // 点击一物一码详情
  const getCode = (row, index) => {
    codeRowObj.value = { ...row, index: index }
    StoreDetailGoodsList.value[index].stockCodeVosTemp = StoreDetailGoodsList.value[
      index
    ].stockCodeVosTemp.map((o) => {
      return { ...o, ...row }
    })
    if (row.stockCodeVos.length > 0) {
      getCodeDialog.value = true
    } else {
      getCodeDataShow()
    }
  }
  // 在库选择弹窗
  const SelectCodeDialog = ref(false)
  const stockCodeVosTemp = ref([]) //在库选择的选中数据
  // 点击在库选择
  const getCodeDataShow = () => {
    stockCodeVosTemp.value = StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp
    SelectCodeDialog.value = true
    nextTick(() => {
      getInStoreCodeListData()
    })
  }

  // 确定选择选中的编码
  const confirmCode = () => {
    if (
      codeRowObj.value.qty !=
      StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp.length
    ) {
      ElMessage({
        showClose: true,
        message: '录入编码不能超过出库编码总数',
        duration: 4000,
        offset: 200,
        type: 'error',
      })
      return
    }
    if (StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp.length == 0) {
      StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp = []
    } else {
      StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVos = StoreDetailGoodsList.value[
        codeRowObj.value.index
      ].stockCodeVosTemp.map((o) => {
        return { code: o.code }
      })
    }

    getCodeDialog.value = false
  }
  // 选择删除选中编码
  const deteleCode = (index) => {
    StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp =
      StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp.filter(
        (o, n) => n != index,
      )
  }
  // 创建编码
  const CreateCodeDialog = ref(false)
  const createCodeRef = ref()
  const createCode = ref({
    codeVos: [
      {
        goodsId: null, //商品ID
        goodsSpecId: null, //商品规格ID
        qty: '1', //生成编码数量
        warrantyDay: '30', //质保周期/天数
      },
    ],
    name: '', //批次名称
    qty: null, //编码数量
    type: 1, //编码类型：1-成品、2-配件
  })
  // 创建编码弹窗按钮
  const onCreateCode = () => {
    CreateCodeDialog.value = true
    createCode.value = {
      codeVos: [
        {
          goodsId: codeRowObj.value.goodsId, //商品ID
          goodsSpecId: codeRowObj.value.goodsSpecId, //商品规格ID
          qty: codeRowObj.value.qty, //生成编码数量
          warrantyDay: '30', //质保周期/天数
        },
      ],
      name: '', //批次名称
      qty: null, //编码数量
      type: codeRowObj.value.type, //编码类型：1-成品、2-配件
    }
  }
  const paginationRef = ref()
  const totalCode = ref(0)
  const getListCode = ref([])
  const selectCodeRef = ref()
  const getInStoreCodeListData = async () => {
    let data = {
      goodsId: codeRowObj.value.goodsId,
      goodsSpecId: codeRowObj.value.goodsSpecId,
      keyword: keywordCode.value,
      limit: paginationRef.value.size,
      page: paginationRef.value.current,
      storeId: null,
      storePositionId: null,
      type: codeRowObj.value.type,
    }
    getStoreCodeListLoading.value = true
    await getStoreCodeList(data).then((res) => {
      if (res) {
        totalCode.value = Number(res.data.data.total)
        getListCode.value = res.data.data.rows
        // // 重新渲染 商品信息选择
        stockCodeVosTemp.value.map((goods) => {
          getListCode.value.map((item) => {
            if (item.id === goods.id) {
              nextTick(() => {
                selectCodeRef.value!.toggleRowSelection(item, undefined)
              })
            }
          })
        })
      }
    })
    getStoreCodeListLoading.value = false
  }
  const selectAllCodeinformation = (val) => {
    if (val.length > 0) {
      val.map((row) => {
        let result = stockCodeVosTemp.value.some((o) => row.id == o.id)
        if (!result) {
          StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp.push(row)
        }
      })
    } else if (val.length == 0) {
      getListCode.value.map((row) => {
        StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp =
          StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp.filter(
            (o) => o.id != row.id,
          )
      })
    }
  }
  const handleClickCodeinformation = (val, row) => {
    let result = val.some((item) => item.id == row.id) //判断是否是 选中
    if (result) {
      StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp.push(row)
    } else {
      StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp =
        StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp.filter(
          (o) => o.id != row.id,
        )
    }
  }
  // 确定选择在库编码
  const confirmSelectCode = () => {
    StoreDetailGoodsList.value[codeRowObj.value.index].stockCodeVosTemp = stockCodeVosTemp.value
    SelectCodeDialog.value = false
    getCodeDialog.value = true
  }
  // 保存
  const onaddSave = async () => {
    if (!createCodeRef.value) return
    await createCodeRef.value.validate((valid) => {
      if (valid) {
        createCode.value.qty = createCode.value.codeVos[0].qty
        let data = _.cloneDeep(createCode.value)

        addSave(data).then((res) => {
          if (res) {
            if (res.data.isError)
              ElMessage({
                showClose: true,
                message: res.data.message,
                duration: 3000,
                offset: 200,
                type: res.data.success ? 'success' : 'error',
              })
            if (res.data.success) {
              CreateCodeDialog.value = false
              // nextTick(() => {
              getInStoreCodeListData()
              // })
            }
          }
        })
      }
    })
  }

  // 合计
  const getSummaries = (param) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '合计'
        return
      }
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => Number.isNaN(value))) {
        if (index == 13) {
          sums[index] = `￥${values
            .reduce((prev, curr) => {
              const value = Number(curr)
              if (!Number.isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            .toFixed(2)}`
        } else if (index == 10 || index == 11) {
          sums[index] = `${values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!Number.isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)}`
        }
      } else {
        sums[index] = ''
      }
    })

    return sums
  }

  const resetForm = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
    outboundDialog.value = false
  }
  // 根据仓库ID获取仓库详情
  const getDetailStoreItem = async () => {
    loading.value = true
    if (route.params.id) {
      await getOutboundDetail(route.params.id).then((res) => {
        if (res) {
          if (res.data.code == 20000) {
            DetailStore.value = res.data.data.row
          } else {
            if (res.data.isError)
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'error',
                duration: 4000,
                offset: 200,
              })
          }
        }
      })
    }
    loading.value = false
  }
  // 地址
  function addressValChange() {
    addrsObj.value = addrsDom.value.getSelectAddr()
    ruleForm.value.sendProvince = addrsObj.value.province
    ruleForm.value.sendCity = addrsObj.value.city
    ruleForm.value.sendArea = addrsObj.value.area
    ruleForm.value.sendTown = addrsObj.value.town
  }
  //商品信息
  const getoutStoreList = async () => {
    loading.value = true
    if (route.params.id) {
      await getOutboundMaterial(route.params.id).then((res) => {
        if (res) {
          if (res.data.code == 20000) {
            StoreDetailGoodsList.value = res.data.data.row.map((o) => {
              return { ...o, stockCodeVosTemp: o.stockCodeVos }
            })
          } else {
            if (res.data.isError)
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'error',
                duration: 4000,
              })
          }
        }
      })
    }
    loading.value = false
  }
  // 人员仓库变化
  const changestoreId = (n) => {
    modules.value.map((o) => {
      if (n == o.id) {
        ruleForm.value.sendName = o.userName
        ruleForm.value.sendPhone = o.phone
        ruleForm.value.sendAddress = o.address
        ruleForm.value.sendProvince = o.province
        ruleForm.value.sendCity = o.city
        ruleForm.value.sendArea = o.area
        ruleForm.value.sendTown = o.town

        addrsObj.value = {
          province: o.province,
          city: o.city,
          area: o.area,
          town: o.town,
        }
      }
    })
  }
  //仓库及人员地址下拉列表查询
  const valuestoreEmpAddress = ref()
  const inputValueSch = _.throttle((val: string) => {
    valuestoreEmpAddress.value = val
  }, 500)
  watch(valuestoreEmpAddress, (n) => {
    getstoreEmpAddressPageSelect(n)
  })
  const modules = ref([])
  const loadingEmp = ref(false)
  // 获取仓库人员及地址下拉
  async function getstoreEmpAddressPageSelect(val) {
    loadingEmp.value = true
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    await storeEmpAddressPageSelect(data, DetailStore.value?.storeType).then((res) => {
      if (res.data.success) {
        modules.value = res.data.data.rows
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            duration: 4000,
            offset: 200,
            type: 'error',
          })
      }
    })
    loadingEmp.value = false
  }
  // 作废
  const cancellationBtn = () => {
    cancellationDialog.value = true
  }

  // 确认作废
  const cancellationConfirm = () => {
    let data = {
      remark: remark.value,
    }
    cancelStoreOutbound(data, route.params.id).then((res) => {
      if (res) {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 4000,
          })
        if (res.data.success) {
          cancellationDialog.value = false
          getDetailStoreItem()
        }
      }
    })
  }
  // 出库
  const outboundBtn = () => {
    outboundDialog.value = true
    getstoreEmpAddressPageSelect('')
    getLogisticsSelectListArr('')
  }
  // 确认出库
  const outboundConfirm = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid) => {
      if (valid) {
        ruleForm.value.outBoundMaterialVos = StoreDetailGoodsList.value.map((o) => {
          return {
            stockCodeVos: o.stockCodeVos,
            goodsId: o.goodsId,
            goodsSpecId: o.goodsSpecId,
            id: o.id,
            price: o.price,
            qty: o.qty,
            remark: o.remark,
            storeId: o.storeId,
            storePositionId: o.storePositionId,
            type: o.type,
          }
        })
        saveSureStoreOutbound(ruleForm.value, route.params.id).then((res) => {
          if (res) {
            if (res.data.isError)
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: res.data.success ? 'success' : 'error',
                duration: 4000,
              })
            if (res.data.success) {
              outboundDialog.value = false
              getDetailStoreItem()
              onOutStoreCancel()
            }
          }
        })
      }
    })
  }
  const Logistics = ref([])
  const logisticsName = ref('')
  const inputValueLog = _.throttle((val: string) => {
    logisticsName.value = val
  }, 500)
  watch(logisticsName, (n) => {
    getLogisticsSelectListArr(n)
  })
  watch(
    () => ruleForm.value.logisticsName,
    (n) => {
      if (n) {
        Logistics.value.map((o) => {
          if (o.name == n) {
            ruleForm.value.logisticsCode = o.code
          }
        })
      } else {
        ruleForm.value.logisticsCode = ''
      }
    },
  )
  // 获取物流列表
  async function getLogisticsSelectListArr(val) {
    loadingEmp.value = true
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    await getLogisticsSelectList(data).then((res) => {
      if (res.data.success) {
        Logistics.value = res.data.data.rows
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            duration: 4000,
            offset: 200,
            type: 'error',
          })
      }
      loadingEmp.value = false
    })
  }

  // 打印
  const printBtn = () => {
    ElMessage({
      showClose: true,
      message: '正在维护升级中，敬请期待...',
      type: 'success',
      duration: 4000,
    })
  }

  /**
   * 出库弹窗表单验证结果
   */
  const outStoreFormValidateResult = ref({
    sendAddress: true,
    sendName: true,
    sendPhone: true,
    sendProvince: true,
  })

  /**
   * 出库弹窗表单验证事件
   */
  const handleOutStoreFormValidate = (prop: FormItemProp, isValid: boolean) => {
    outStoreFormValidateResult.value[prop as string] = isValid
  }

  /**
   * 出库弹窗取消事件
   */
  const onOutStoreCancel = () => {
    resetForm()
    outStoreFormValidateResult.value = {
      sendAddress: true,
      sendName: true,
      sendPhone: true,
      sendProvince: true,
    }
  }

  onMounted(async () => {
    new Promise(() => {
      getDetailStoreItem()
      getoutStoreList()
    })
  })
</script>

<style lang="scss" scoped>
  @import './detail';
</style>
